package com.book.shop.controller;

import com.book.shop.Webservice.BookService;
import com.book.shop.model.Book;
import com.book.shop.model.form.BookForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    //查询所有图书
    @GetMapping (value = {"/home","/"})
    public String ListAllBooks(Model model){
        List<Book> books = bookService.findAllBooks();
        model.addAttribute("books",books);
        return "index";
    }
    //搜索功能
    @GetMapping(value = "/search")
    public String searchBooks(@RequestParam(name = "Search",defaultValue = "") String query,Model model){
        List<Book> books = bookService.searchBooks(query);
        model.addAttribute("books",books);
        return "book/search";
    }
    //设置图书图片类型
    @GetMapping("/bookImage")
    public void bookImage(HttpServletResponse response,@RequestParam("bookId") Long bookId) throws IOException{
         Book book = bookService.findBookById(bookId);
         if(book != null){
             response.setContentType("image/jpeg");
             response.getOutputStream().write(book.getBookImage());
         }
         response.getOutputStream().close();
    }
    //通过图书id查找图书
    @GetMapping(value = "/books/{bookId:\\d+}")
    public String getBook(@PathVariable Long bookId,Model model) throws Exception{
        Book book = bookService.findBookById(bookId);
        try{
            model.addAttribute("book",book);
        }catch (Exception e){
            throw new Exception("找不到该图书");
        }
        return "book/book";
    }

    //获取图书信息
    @GetMapping("/books")
    @Secured("ROLE_ADMIN")
    public String getBooks(Model model){
        List<Book> books =bookService.findAllBooks();
        model.addAttribute("books",books);
        return "book/showAllBooks";
    }

    //添加图书
    @GetMapping("/books/add")
    @Secured("ROLE_ADMIN")
    public String addBookPage(Model model){
        BookForm bookForm =new BookForm();
        model.addAttribute("bookForm",bookForm);
        return "book/addBook";
    }

    //添加图书
    @PostMapping("books/add")
    @Secured("ROLE_ADMIN")
    public String addBook(@ModelAttribute BookForm bookForm,Model model,BindingResult result){
        if(result.hasErrors()){
            List<ObjectError> ls = result.getAllErrors();
            for (int i = 0; i < ls.size(); i++) {
                System.out.println("error:"+ls.get(i));
            }
        }
        Book savedBook = bookService.saveBook(bookForm);
        model.addAttribute("successMessage","图书创建编号"+savedBook.getBookId());
        return addBookPage(model);
    }

    //通过图书id编辑图书
    @GetMapping("/books/edit/{bookId}")
    @Secured("ROLE_ADMIN")
    public String editBookPage(@PathVariable Long bookId,Model model){
        Book book = bookService.findBookById(bookId);
        model.addAttribute("bookForm",new BookForm(book));
        return "book/editBook";
    }

    //编辑图书
    @PostMapping("books/edit")
    @Secured("ROLE_ADMIN")
    public String editBookPage(@ModelAttribute BookForm bookForm,Model model){
        Book saveBook = bookService.saveBook(bookForm);
        model.addAttribute("successMessage","图书信息编辑成功"+saveBook.getBookId());
        return "book/editBook";
    }

    //通过id删除图书
    @GetMapping("books/delete/{bookId}")
    @Secured("ROLE_ADMIN")
    public String deleteBook(@PathVariable Long bookId,RedirectAttributes redirectAttributes){
        Book book = bookService.findBookById(bookId);
        bookService.deleteBook(book);
        redirectAttributes.addFlashAttribute("successMessage","图书编号"+bookId+"删除成功");
//        model.addAttribute("successMessage","图书编号"+bookId+"删除成功");
        return "redirect:/books";
    }

    //图书预览
    @GetMapping("/book/view/{bookId}")
    @Secured("ROLE_ADMIN")
    public String viewBook(@PathVariable Long bookId,Model model){
        Book book = bookService.findBookById(bookId);
        model.addAttribute("book",book);
        return "book/viewBook";
    }

}
